package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.rh.bmw4s.R;
import com.rh.bmw4s.adapter.CarAdapter;
import com.rh.bmw4s.bean.BaseBean;
import com.rh.bmw4s.bean.BrandBean;
import com.rh.bmw4s.bean.CarBean;
import com.rh.bmw4s.bean.MyHashMap;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.DealResult;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class BuyCarActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.title_right_one_btn)
    ImageView titleRightOneBtn;
    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.tv_brand)
    TextView tvBrand;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_choose)
    TextView tvChoose;
    @BindView(R.id.ll_choose)
    LinearLayout llChoose;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    Unbinder unbinder;
    @BindView(R.id.title_left_one_tv)
    TextView titleLeftOneTv;
    @BindView(R.id.tv_buycar_reset)
    TextView tvReset;
    @BindView(R.id.rel_buycar_reset)
    RelativeLayout relReset;
    private boolean isPriceUp = false;
    PopupWindow popAll;
    private View emptyView;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private CarAdapter mAdapter;
    private String ids = "";
    private String ids1 = "";
    private int type = 0;
    private int page = 0;
    private int count = 0;
    private int requestNum = 10;

    //3 汽车用品接口  4轮胎接口
    private int exters;
    private int mysearchtype;
    private int anInt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_car);
        ButterKnife.bind(this);
        anInt = SPUtils.getInstance().getInt(ConfigValue.userId);

        Intent i = getIntent();
        cateId = i.getIntExtra("id", 0);
        String title = i.getStringExtra("name");
        exters = i.getIntExtra("exters", 0);
        mysearchtype = i.getIntExtra("mysearchtype", 0); //汽车用品和汽车轮胎也是跳转到该界面，但是跳转到搜索界面时不同


        tvMiddleTitle.setText(title);
        emptyView = findViewById(R.id.empty_buycar);
        initView();
    }

    private void initView() {
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        titleRightOneBtn.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new GridLayoutManager(BuyCarActivity.this, 2));
        //指导价显示不同
        if (exters == 3) {
            mAdapter = new CarAdapter(BuyCarActivity.this, 3);
        } else if (exters == 4) {
            mAdapter = new CarAdapter(BuyCarActivity.this, 4);
        } else {
            mAdapter = new CarAdapter(BuyCarActivity.this, 0);
        }

        mAdapter.setDataList(new ArrayList<CarBean>());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        //divider
        GridItemDecoration divider = new GridItemDecoration.Builder(BuyCarActivity.this)
                .setHorizontal(R.dimen.size_10dp)
                //.setVertical(R.dimen.size_10dp)
                .setColorResource(R.color.app_bg1)
                .build();
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(divider);

        //设置头部加载颜色  刷新图标颜色  字体颜色  背景颜色
        recyclerView.setHeaderViewColor(R.color.white, R.color.white, R.color.app_bg1);
        //设置底部加载颜色
        recyclerView.setFooterViewColor(R.color.white, R.color.white, R.color.app_bg1);
        //设置底部加载文字提示
        recyclerView.setFooterViewHint("努力加载中", "已经全部加载", "网络不给力啊");

        recyclerView.setLoadMoreEnabled(true);
        recyclerView.setPullRefreshEnabled(false);

        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (count < ((page + 1) * requestNum)) {  //不满一页会多加数据
                    recyclerView.setNoMore(true);
                } else {
                    page++;
                    getDatas();
                }
            }
        });

        getDatas();
        DialogUtils.showProgressDlg(BuyCarActivity.this, "努力加载中......");

        //点击item跳转详情
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mAdapter.getDataList().size() > position) {
                    CarBean carBean = mAdapter.getDataList().get(position);
                    Intent intent = new Intent(BuyCarActivity.this, WebShowActivity.class);
                    // intent.putExtra("url", "http://4s.liexianghudong.com/index.php/home/index/xiangqing/id/" + carBean.getId() + "/mem_id/" + anInt);
                    intent.putExtra("url", Constant.H5DETAILS + carBean.getId() + "/mem_id/" + anInt);
//                    if (exters == 3 || exters == 4) {
//                        //轮胎和汽车用品详情页
//                        intent.putExtra("url", "http://4s.liexianghudong.com/index.php/home/index/qixiang/id/" + carBean.getId() + "/mem_id/" + anInt);
//                    } else {
//                        //二手车详情页
//                        intent.putExtra("url", "http://4s.liexianghudong.com/index.php/home/index/ershouxiang/id/" + carBean.getId() + "/mem_id/" + anInt);
//                    }
                    BuyCarActivity.this.startActivity(intent);
                }
            }

        });
    }

    private int cateId;
    private String carBrand = "";
    private String carType = "";
    private String price = "";
    private String kilo = "";
    private String year = "";
    private String pai = "";
    private String gearbox = "";
    private String engin = "";
    private String standard = "";
    private String carSource = "";
    private String color = "";
    private String area = "";


    PostRequest<String> request = null;

    private void getDatas() {
        recyclerView.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);

        if (exters == 4) {
            request = OkGo.<String>post(Constant.LunTai);
        } else if (exters == 3) {
            request = OkGo.<String>post(Constant.Automotive);
        } else {
            request = OkGo.<String>post(Constant.OldCarSort)
                    .params("cate_id", cateId);
            LogUtils.d("id", cateId);
        }
        request.tag(this)
                .params("type", type)
                .params("car_brand", carBrand)
                .params("car_type", carType)
                .params("price", price)
                .params("kilo", kilo)
                .params("year", year)
                .params("pai", pai)
                .params("gearbox", gearbox)
                .params("engin", engin)
                .params("standard", standard)
                .params("car_source", carSource)
                .params("color", color)
                .params("area", area)
                .params("page", page)
                .params("count", requestNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<CarBean> bean = DealResult.getInstace().dealData(BuyCarActivity.this, response, new TypeToken<BaseBean<CarBean>>() {
                        }.getType());
                        if (page == 0 && bean.getDatas().size() == 0) {
                            recyclerView.setVisibility(View.GONE);
                            emptyView.setVisibility(View.VISIBLE);
                            return;
                        }
                        List<CarBean> beans = bean.getDatas();
                        setDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(BuyCarActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void setDatas(List<CarBean> beans) {
        mAdapter.addAll(beans);
        count = mAdapter.getItemCount();
        recyclerView.refreshComplete(requestNum);
    }


    @OnClick({R.id.tv_buycar_reset, R.id.title_left_one_btn, R.id.title_right_one_btn, R.id.tv_all, R.id.tv_brand
            , R.id.tv_price, R.id.tv_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_buycar_reset:  //重置按钮
                relReset.setVisibility(View.GONE);
                tvAll.setText("综合排序");
                carBrand = ""; //品牌设置为空
                type = 0;
                sortAgain();
                break;
            case R.id.title_left_one_btn:
                this.finish();
                break;
            case R.id.title_right_one_btn:
                Intent intent = new Intent(BuyCarActivity.this, SearchActivity.class);
                if (mysearchtype == 4) {
                    //汽车用品搜索界面
                    intent.putExtra("searchtype", 4);
                } else if (mysearchtype == 5) {
                    //汽车轮胎搜索界面
                    intent.putExtra("searchtype", 5);
                } else {
                    intent.putExtra("cat_id", cateId);
                    LogUtils.d("bbb", cateId);
                    intent.putExtra("searchtype", 2);
                }
                startActivity(intent);
                break;
            case R.id.tv_all:
                showAllPop();
                break;
            case R.id.tv_brand:
                startActivityForResult(new Intent(BuyCarActivity.this, CategoryActivity.class), 0);
                break;
            case R.id.tv_price:
                if (isPriceUp) {
                    isPriceUp = false;
                    type = 1;
                    sortAgain();
                } else {
                    isPriceUp = true;
                    type = 2;
                    sortAgain();
                }
                break;
            case R.id.tv_choose:
                startActivityForResult(new Intent(BuyCarActivity.this, FilterActivity.class), 0);
                break;
        }
    }

    private void showAllPop() {
        View contentView = LayoutInflater.from(BuyCarActivity.this).inflate(R.layout.pop_rank, null);
        popAll = new PopupWindow(BuyCarActivity.this);
        popAll.setContentView(contentView);
        popAll.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popAll.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popAll.setFocusable(true);
        popAll.setOutsideTouchable(true);
        popAll.showAsDropDown(llChoose);
        contentView.findViewById(R.id.tv_default).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tvAll.setText("综合排序");
                popAll.dismiss();
                type = 0;
                sortAgain();
            }
        });

        contentView.findViewById(R.id.tv_mileage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tvAll.setText("里程最短");
                popAll.dismiss();
                type = 3;
                sortAgain();
            }
        });
        contentView.findViewById(R.id.tv_year).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tvAll.setText("车龄最短");
                popAll.dismiss();
                type = 4;
                sortAgain();
            }
        });
    }

    private void sortAgain() {
        DialogUtils.showProgressDlg(BuyCarActivity.this, "努力加载中......");
        recyclerView.setNoMore(false);  //这里
        mAdapter.clear();
        page = 0;
        lRecyclerViewAdapter.notifyDataSetChanged();
        getDatas();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.SUCESS_BRAND:
                relReset.setVisibility(View.VISIBLE); //显示重置按钮
                //先全部置空
                makeNull();

                BrandBean.BrandsBean bean = (BrandBean.BrandsBean) data.getSerializableExtra("bean");
                //tvBrand.setText(bean.getModel_name());
                carBrand = bean.getId() + "";
                sortAgain();
                break;
            case Constant.SUCESS_FILTRE:
                //先全部置空
                DialogUtils.showProgressDlg(BuyCarActivity.this, "努力加载中......");
                relReset.setVisibility(View.GONE);
                recyclerView.setNoMore(false);  //这里
                mAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();

                makeNull();

                Bundle bundle = data.getExtras();
                MyHashMap myHashMap = (MyHashMap) bundle.get("maps");
                HashMap<String, String> map = myHashMap.getMap();
                Iterator iterator = map.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    String title = entry.getKey().toString();
                    Log.d("CCC", "--" + title);
                    if (title.contains("品牌")) {
                        carBrand = entry.getValue().toString();
                    } else if (title.contains("车辆级别")) {
                        carType = entry.getValue().toString();
                    } else if (title.contains("价格")) {
                        price = entry.getValue().toString();
                    } else if (title.contains("里程")) {
                        kilo = entry.getValue().toString();
                    } else if (title.contains("年限")) {
                        year = entry.getValue().toString();
                    } else if (title.contains("排量")) {
                        pai = entry.getValue().toString();
                    } else if (title.contains("变速箱")) {
                        gearbox = entry.getValue().toString();
                    } else if (title.contains("发动机")) {
                        engin = entry.getValue().toString();
                    } else if (title.contains("排放标准")) {
                        standard = entry.getValue().toString();
                    } else if (title.contains("车源")) {
                        carSource = entry.getValue().toString();
                    } else if (title.contains("颜色")) {
                        color = entry.getValue().toString();
                        if (color.endsWith(",")) {
                            color = color.substring(0, color.length() - 1);
                        }
                    } else if (title.contains("产地")) {
                        area = entry.getValue().toString();
                    }
                }
                getDatas();
                break;
        }
    }

    /**
     * 将参数重置
     */
    private void makeNull() {
        page = 0;
        type = 0;

        carBrand = "";
        carType = "";
        price = "";
        kilo = "";
        year = "";
        pai = "";
        gearbox = "";
        engin = "";
        standard = "";
        carSource = "";
        color = "";
        area = "";
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (popAll != null) {
            popAll.dismiss();
        }
    }

}
